package com.zx.filter;

import com.zx.bean.User;
import com.zx.web.service.UserService;
import com.zx.web.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.filter
 * @Description:
 * @Date 2022/9/13 17:31
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取登录状态(说明已登录)
        Object userSession = req.getSession().getAttribute("user");
        if(userSession!=null){
            filterChain.doFilter(req,resp);
            return;
        }

        String requestURI = req.getRequestURI();
        if ("/login.jsp".equalsIgnoreCase(requestURI)||
                "/userservlet".equalsIgnoreCase(requestURI)||
                "/register.jsp".equalsIgnoreCase(requestURI)||
                requestURI.startsWith("/js")||
                requestURI.startsWith("/image")||
                requestURI.startsWith("/css")

        ){
            filterChain.doFilter(req,resp);
            return;
        }

        //获取cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if("user".equalsIgnoreCase(cookie.getName())){
                    String value = cookie.getValue();
                    String decode = URLDecoder.decode(value, "utf-8");
                    String[] split = decode.split("#");
                    UserService service = new UserServiceImpl();
                    User user = service.login(split[0], split[1]);
                    if(user!=null){
                        req.getSession().setAttribute("user",user);
                    }
                    filterChain.doFilter(req,resp);
                    return;
                }
            }
        }

        resp.sendRedirect("/login.jsp");

    }

    @Override
    public void destroy() {

    }
}
